package cn.lili.modules.order.order.serviceimpl;

import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.modules.member.client.VipClient;
import cn.lili.modules.member.client.VipConfigClient;
import cn.lili.modules.order.order.mapper.VipOrderMapper;
import cn.lili.modules.order.order.service.VipOrderService;
import cn.lili.modules.order.order.entity.dos.VipOrder;
import cn.lili.modules.system.entity.dos.LiVip;
import cn.lili.modules.system.entity.dos.LiVipConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
@RequiredArgsConstructor
public class VipOrderServiceImpl extends ServiceImpl<VipOrderMapper, VipOrder>
        implements VipOrderService {

    @Resource
    private VipConfigClient vipConfigClient;

    private final VipClient vipClient;

    @Override
    public VipOrder createOrder() {
        LiVip vip = vipClient.getByUserId(UserContext.getCurrentId());
        if (null != vip && vip.getVipStatus() == 3) {
            throw new ServiceException("用户会员已冻结，无法开通或续费会员");
        }
        LiVipConfig vipConfig = vipConfigClient.getByDefault();
        if (vipConfig == null) {
            throw new ServiceException("未获取到，会员价格");
        }
        VipOrder vipOrder = new VipOrder(vipConfig.getVipPrice().doubleValue());
        save(vipOrder);
        return vipOrder;
    }

    @Override
    public VipOrder getBySn(String sn) {
        LambdaQueryWrapper<VipOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VipOrder::getSn, sn);
        queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }
}
